package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.qxsjz.entity.MergeTransLog;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.constant.MergeErrorState;
import net.wantongtech.xa.uploadbasicinfo.dao.CommonBaseDao;
import net.wantongtech.xa.uploadbasicinfo.dao.MarkMergeTransStateDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 标记合并交易状态服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/20
 */
@Slf4j
@Service
public class MarkMergeTransStateService {

    @Resource
    private MarkMergeTransStateDao markMergeTransStateDao;

    @Resource
    private CommonBaseDao commonBaseDao;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    public void mark() {
        List<MergeTransLog> mergeTransLogs = markMergeTransStateDao.queryAllErrorMergeLog();
        log.info("共查询出{}条合并交易日志", mergeTransLogs.size());
        if (mergeTransLogs.isEmpty()) {
            return;
        }

        mergeTransLogs.forEach(mergeTransLog -> taskExecutor.execute(new MarkMergeTransStateThread(mergeTransLog)));

    }


    public class MarkMergeTransStateThread implements Runnable {

        private final MergeTransLog mergeTransLog;

        MarkMergeTransStateThread(MergeTransLog mergeTransLog) {
            this.mergeTransLog = mergeTransLog;
        }

        @Override
        public void run() {
            String cardNo = mergeTransLog.getCardNo();
            int markState = 0;
            if (!cardNo.startsWith("61")) {
                markState = MergeErrorState.OTHER_CARD.getValue();
            } else if ("61010000000000000000".equals(cardNo)) {
                markState = MergeErrorState.DEFAULT_CARD.getValue();
            } else {
                String cardNetId = cardNo.substring(0, 4);
                String eCardNo = cardNo.substring(4);
                CardInfo cardInfo = commonBaseDao.queryCardInfoByECardNo(eCardNo);
                if (cardInfo != null) {
                    Integer rightCardNetId = cardInfo.getCardNetID();
                    if (!Objects.equals(Integer.valueOf(cardNetId), rightCardNetId)) {
                        markState = MergeErrorState.NETNO_ERROR.getValue();
                    }
                } else {
                    markState = MergeErrorState.NO_CARD.getValue();
                }
            }
            log.info("passId：{}，卡号：{}，标记状态：{}", mergeTransLog.getPassId(), cardNo, markState);
            markMergeTransStateDao.updateErrorMergeLogState(mergeTransLog, markState);
        }


    }
}
